<template>
	<view class="content">
		<view class="logo-area">
			<image class="logo" src="/static/logo.png"></image>
			<text class="app-name">缘拾</text>
		</view>

		<view class="login-area" v-if="!userInfo">
			<button class="wechat-login-btn" type="primary" @click="wechatLogin">微信用户一键登录</button>
			<button class="phone-login-btn" open-type="getPhoneNumber"
				@getphonenumber="onGetPhoneNumber">手机号登录/注册</button>
			<view class="agreement-area">
				<checkbox class="agreement-checkbox" :checked="agreementChecked" @tap="changeAgreement"></checkbox>
				<text class="agreement-text">我已经同意如初用户协议与隐私条款</text>
			</view>
		</view>

		<view class="user-info" v-if="userInfo">
			<text class="user-text">登录成功！用户ID: {{ userInfo.userId }}</text>
			<text v-if="userInfo.phoneNumber" class="user-text">手机号: {{ userInfo.phoneNumber }}</text>
			<button class="logout-btn" type="default" @click="logout">退出登录</button>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 响应式数据
const userInfo = ref(null);
const token = ref('');
const code = ref(''); // 登录凭证
const agreementChecked = ref(false);

// 检查登录状态
const checkLoginStatus = () => {
	const storedToken = uni.getStorageSync('token');
	const storedUserInfo = uni.getStorageSync('userInfo');
	if (storedToken && storedUserInfo) {
		token.value = storedToken;
		userInfo.value = storedUserInfo;
		console.log('已登录用户:', storedUserInfo);
		
		// 检查用户是否已经完善个人资料
		if (!userInfo.value.gender || !userInfo.value.birthYear || !userInfo.value.address) {
			// 未完善资料，跳转到个人资料页面
			setTimeout(() => {
				uni.navigateTo({url: '/pages/profile/profile'})
			}, 500);
		} else {
			// 已完善资料，跳转到个人中心页面
			setTimeout(() => {
				uni.switchTab({url: '/pages/center/index'})
			}, 500);
		}
	}
};

// 在页面加载时检查登录状态
onLoad(() => {
	checkLoginStatus();
});

// 切换协议选中状态
const changeAgreement = () => {
	console.log('当前协议状态:', agreementChecked.value);
	// 在tap事件中手动切换选中状态
	agreementChecked.value = !agreementChecked.value;
	console.log('协议状态已更改为:', agreementChecked.value);
};

// 获取登录code
const getLoginCode = async () => {
	try {
		const loginRes = await uni.login({
			provider: 'weixin'
		});
		console.log(loginRes);

		if (loginRes.code) {
			code.value = loginRes.code;
		}
	} catch (error) {
		console.error('获取code失败:', error);
	}
};

// 微信登录
const wechatLogin = () => {
	if (!agreementChecked.value) {
		uni.showToast({
			title: '请先同意用户协议与隐私条款',
			icon: 'none'
		});
		return;
	}

	uni.showLoading({
		title: '登录中...'
	});

	// 调用微信登录API获取code
	uni.login({
		provider: 'weixin',
		success: (res) => {
			console.log('微信登录成功:', res);
			
			if (res.code) {
				// 调用云函数进行登录验证
				uniCloud.callFunction({
					name: 'wechat-login',
					data: {
						code: res.code
					},
					success: (result) => {
						uni.hideLoading();
						console.log('登录结果:', result.result);
						if (result.result.code === 0) {
							// 登录成功，保存token、过期时间和用户信息
					token.value = result.result.token;
					userInfo.value = result.result;

					uni.setStorageSync('token', token.value);
					// 保存token过期时间
					if (result.result.tokenExpired) {
						uni.setStorageSync('tokenExpired', result.result.tokenExpired);
					}
					// 保存用户信息时，确保不包含敏感信息
					const safeUserInfo = {
						userId: result.result.userId,
						userInfo: result.result.userInfo,
						nickname: result.result.userInfo.nickname || '',
						avatar: result.result.userInfo.avatar || '',
						gender: result.result.userInfo.gender || 0,
						birthYear: result.result.userInfo.birthYear || '',
						address: result.result.userInfo.address || ''
					};
					uni.setStorageSync('userInfo', safeUserInfo);

							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});

							// 检查用户是否已经完善个人资料
							if (!userInfo.value.gender || !userInfo.value.birthYear || !userInfo.value.address) {
								// 未完善资料，跳转到个人资料页面
								setTimeout(() => {
									uni.navigateTo({
										url: '/pages/profile/profile'
									});
								}, 1500);
							} else {
								// 已完善资料，跳转到个人中心页面
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/center/index'
									});
								}, 1500);
							}
					} else {
						// 登录失败
						uni.hideLoading();
						uni.showToast({
							title: result.result.message || '登录失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					uni.hideLoading();
					console.error('调用云函数失败:', err);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				}
			});
			} else {
				uni.hideLoading();
				uni.showToast({
					title: '获取微信code失败',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			console.error('微信登录失败:', err);
			uni.showToast({
				title: '微信授权失败',
				icon: 'none'
			});
		}
	});
};

// 手机号授权登录
const onGetPhoneNumber = async (e) => {
	// 检查用户是否授权
	if (!e.detail.errMsg?.endsWith('ok')) {
		uni.showToast({
			title: '已取消授权',
			icon: 'none'
		});
		return;
	}

	if (!agreementChecked.value) {
		uni.showToast({
			title: '请先同意用户协议与隐私条款',
			icon: 'none'
		});
		return;
	}

	uni.showLoading({
		title: '登录中...'
	});

	// 确保有code
	if (!code.value) {
		try {
			await getLoginCode();
		} catch (error) {
			uni.hideLoading();
			console.error('获取code失败:', error);
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			});
			return;
		}
	}

	// 调用手机号登录云函数
	uniCloud.callFunction({
		name: 'phone-login',
		data: {
			code: code.value,
			encryptedData: e.detail.encryptedData,
			iv: e.detail.iv
		},
		success: (result) => {
			uni.hideLoading();
			console.log('手机号登录结果:', result.result);
			if (result.result.code === 0) {
				// 登录成功，保存token、过期时间和用户信息
					token.value = result.result.token;
					userInfo.value = result.result;

					uni.setStorageSync('token', token.value);
					// 保存token过期时间
					if (result.result.tokenExpired) {
						uni.setStorageSync('tokenExpired', result.result.tokenExpired);
					}
					// 保存用户信息时，确保不包含敏感信息
					const safeUserInfo = {
						userId: result.result.userId,
						userInfo: result.result.userInfo,
						nickname: result.result.userInfo.nickname || '',
						avatar: result.result.userInfo.avatar || '',
						gender: result.result.userInfo.gender || 0,
						birthYear: result.result.userInfo.birthYear || '',
						address: result.result.userInfo.address || '',
						phoneNumber: result.result.phoneNumber
					};
					uni.setStorageSync('userInfo', safeUserInfo);

				uni.showToast({
					title: '登录成功',
					icon: 'success'
				});

				// 检查用户是否已经完善个人资料
				if (!userInfo.value.gender || !userInfo.value.birthYear || !userInfo.value.address) {
					// 未完善资料，跳转到个人资料页面
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/profile/profile'
						});
					}, 1500);
				} else {
					// 已完善资料，跳转到个人中心页面
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/center/index'
						});
					}, 1500);
				}
			} else {
				// 登录失败
				uni.showToast({
					title: result.result.message || '登录失败',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			uni.hideLoading();
			console.error('调用云函数失败:', err);
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			});
		}
	});
};

// 退出登录
const logout = () => {
	token.value = '';
	userInfo.value = null;
	uni.removeStorageSync('token');
	uni.removeStorageSync('userInfo');
	uni.showToast({
		title: '已退出登录',
		icon: 'success'
	});
};
</script>

<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx;
	min-height: 100vh;
	box-sizing: border-box;
}

.logo-area {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-top: 100rpx;
	margin-bottom: 80rpx;
}

.logo {
	height: 220rpx;
	width: 220rpx;
	border-radius: 40rpx;
}

.app-name {
	margin-top: 30rpx;
	font-size: 48rpx;
	font-weight: bold;
	color: #6d4aff;
}

.login-area {
	width: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.wechat-login-btn {
	width: 100%;
	height: 100rpx;
	line-height: 100rpx;
	font-size: 36rpx;
	background-color: #6d4aff;
	color: white;
	border-radius: 50rpx;
	margin-bottom: 30rpx;
}

.phone-login-btn {
	width: 100%;
	height: 100rpx;
	line-height: 100rpx;
	font-size: 36rpx;
	background-color: white;
	color: #6d4aff;
	border: 2rpx solid #6d4aff;
	border-radius: 50rpx;
	margin-bottom: 40rpx;
}

.agreement-area {
	display: flex;
	align-items: center;
	margin-bottom: 50rpx;
}

.agreement-checkbox {
	transform: scale(0.8);
	margin-right: 10rpx;
}

.agreement-text {
	font-size: 28rpx;
	color: #8f8f94;
}

.user-info {
	margin-top: 40rpx;
	padding: 30rpx;
	background-color: #f0f0f0;
	border-radius: 10rpx;
	width: 100%;
	text-align: center;
}

.user-text {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 15rpx;
}

.logout-btn {
	margin-top: 20rpx;
}
</style>
